package cn.online.taxi.order.dispatch.service.impl;

import cn.online.taxi.common.constant.RedisKeyConstant;
import cn.online.taxi.common.jedis.JedisClient;
import cn.online.taxi.common.utils.RandomNumUtil;
import cn.online.taxi.manager.dto.front.Order;
import cn.online.taxi.order.dispatch.service.DispatchService;
import com.alibaba.dubbo.config.annotation.Service;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.List;

/**
 * @Author BinBini
 * @Date 2021/4/7 19:56
 * @Version 1.0
 */
@Service
public class DispatchServiceImpl implements DispatchService {

    @Autowired
    private JedisClient jedisClient;
    @Value("1500")
    private Integer ORDER_DISPATCH_EXPIRE;

    @Override
    public Order dispatch(long passengerInfoId, String passengerPhone, String userLongitude,
                            String userLatitude, String startLongitude, String startLatitude,
                            String startAddress, String endAddress, String endLongitude,
                            String endLatitude, String passengerToken) {
        Order order = new Order();
        order.setPassengerInfoId(passengerInfoId);
        order.setPassengerPhone(passengerPhone);
        order.setUserLongitude(userLongitude);
        order.setUserLatitude(userLatitude);
        order.setStartLongitude(startLongitude);
        order.setStartLatitude(startLatitude);
        order.setStartAddress(startAddress);
        order.setEndAddress(endAddress);
        order.setEndLongitude(endLongitude);
        order.setEndLatitude(endLatitude);
        if (order == null || "".equals(order.getOrderNumber()) || "".equals(order.getPassengerInfoId())) {
            return null;
        }
        order.setOrderNumber(RandomNumUtil.getNumber(0, 16));
        order.setDriverStatus(0);
        order.setStartTime(new Date());
        order.setIsPaid(0);
        order.setIsCancel(0);
        order.setStatus(1);
        order.setPassengerToken(passengerToken);
        // 派单信息写入redis, key: "GRAB_LOCK_ORDER:orderNumber" value: "order"
        jedisClient.set(RedisKeyConstant.GRAB_LOCK_ORDER_KEY_PRE + ":" + order.getOrderNumber(), new Gson().toJson(order));
        jedisClient.expire(RedisKeyConstant.GRAB_LOCK_ORDER_KEY_PRE + ":" + order.getOrderNumber(), ORDER_DISPATCH_EXPIRE);
        return order;
    }
}
